package encondingFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class VisitFilter  implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hsr = (HttpServletRequest) servletRequest;
        HttpServletResponse hsre = (HttpServletResponse)  servletResponse;

        String url = hsr.getRequestURI();
        if (url.contains("admin")){
            int role = -1;
            if (hsr.getSession().getAttribute("role") != null){
                role =  (int) hsr.getSession().getAttribute("role");
            }
            if (role != 1){
                hsr.getSession().setAttribute("error","Invalid visit!");
                hsre.sendRedirect("/Day03/employee/index.jsp");
            }
        }
        if (url.contains("common")){
            int role = -1;
            if (hsr.getSession().getAttribute("role") != null){
                role =  (int) hsr.getSession().getAttribute("role");
            }
            if (role != 0){
                hsr.getSession().setAttribute("error","Invalid visit!");
                hsre.sendRedirect("/Day03/employee/index.jsp");
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
